<?php
/**
 * User: taodf
 * Date: 17-4-29
 * Time: 下午2:24
 */

namespace Zeus\View\Engines;

use League\Plates\Engine as Plate;

class PlateEngine implements EngineInterface
{
    /**
     * plate实现引擎
     *
     * @var Plate $engine
     */
    private $engine;

    /**
     * 视图模板的名称
     *
     * @var string $view
     */
    private $view;

    /**
     * 视图模板中的变量
     *
     * @var array $param
     */
    private $param;

    /**
     * PlateEngine constructor.
     * @param string $path 模板文件目录
     */
    public function __construct($path)
    {
        $this->engine = new Plate($path);
        if(!is_null($this->engine)){
            $this->engine->setFileExtension("php");
        }
    }

    /**
     * 向视图引擎中添加新的模板目录
     *
     * @param string $name
     * @param string $path
     * @return mixed
     */
    public function names($name, $path)
    {
        $this->engine->addFolder($name, $path);
        return $this;
    }

    /**
     * 为视图引擎注册新的功能
     *
     * @param string $name
     * @param callable $callable
     * @return mixed
     */
    public function feature($name, $callable)
    {
        $this->engine->registerFunction($name,$callable);
        return $this;
    }

    /**
     * 向视图引擎全局空间注入变量
     *
     * @param string $name
     * @param mixed $value
     * @return mixed
     */
    public function share($name, $value)
    {
        $this->engine->addData([$name=>$value]);
        return $this;
    }

    /**
     * 使用视图引擎渲染试图文件
     *
     * @param string $view
     * @param array $param
     * @return string
     */
    public function render($view, $param = [])
    {
        $this->view=$view;
        if(!is_null($this->param)){
            $param=array_merge($param, $this->param);
        }
        return $this->engine->render($view, $param);
    }

    /**
     * 向视图引擎中注入变量
     *
     * @param string $name
     * @param mixed $value
     * @return mixed
     */
    public function with($name, $value)
    {
        $this->param=array_merge($this->param, [$name=>$value]);
        return $this;
    }

    /**
     * 渲染视图
     *
     * @return string
     */
    public function __toString()
    {
        return $this->render($this->view, $this->param);
    }
}